import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
// 路由懒加载
const Login = () => import('@/views/Login/index.vue')
const Layout = () => import('@/layout/index.vue')
const Home = () => import('@/views/Home')
const Category = () => import('@/views/categoty/index.vue')
const Cart = () => import('@/views/Cart/index.vue')
const Search = () => import('@/views/Search/index.vue')
const Goods = () => import('@/views/Goods/index.vue')
const User = () => import('@/views/User/index.vue')
const Checkout = () => import('@/views/checkout')
const Pay = () => import('@/views/pay/index.vue')
const Result = () => import('@/views/pay/result.vue')
// 路由规则数组
const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home },
      { path: '/category/:id', component: Category },
      { path: '/cart', component: Cart },
      { path: '/search', component: Search },
      { path: '/goods/:id', component: Goods },
      { path: '/user', component: User },
      { path: '/user/checkout', component: Checkout },
      { path: '/user/pay', component: Pay },
      { path: '/user/pay/result', component: Result }
    ]
  }
]

// 1.createRouter函数是router实例
// 2.createWebHashHistory：创建hash模式的路由
const router = createRouter({
  // history配置路由模式：hishistory，hash
  history: createWebHashHistory(),
  routes,
  // 配置跳转路由界面滚动位置
  scrollBehavior(to, from, sever) {
    // 前进回退执行，回到之前滚动到的位置
    if (sever) {
      return sever
    } else {
      // 没有浏览过得路由，跳转始终滚动到顶部
      return { top: 0 }
    }
  }
})
// 访问权限控制
router.beforeEach((to, from, next) => {
  const { token } = store.state.user.profile
  // 跳转去user开头的地址却没有登录
  // startsWith查看字符串中是否有以什麽开头的字符
  if (to.path.startsWith('/user') && !token) {
    // to.fullPath：里面包含跳转路径以及路径参数信息
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})

export default router
